/**
 * feibiao.js - 非标电机档案管理模块
 */

// API基本路径
const FEIBIAO_API_BASE = '/api/feibiao';

// 路径映射 - 确保前端调用与后端API匹配
const API_PATHS = {
    motorBase: 'motor-base'        // 对应 AmArchivesBaseController - @RequestMapping("/api/feibiao/motor-base")
};

// 日期格式化
function formatDateTime(date) {
    if (!date) return '--';
    
    try {
        const dateObj = new Date(date);
        if (isNaN(dateObj.getTime())) return '--';
        
        // 格式化日期部分
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        
        // 对于带时间的日期，添加时间部分
        if (date.includes('T') || date.includes(':')) {
            const hours = String(dateObj.getHours()).padStart(2, '0');
            const minutes = String(dateObj.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 只有日期部分
        return `${year}-${month}-${day}`;
    } catch (e) {
        console.error('日期格式化错误:', e);
        return '--';
    }
}

// 格式化数字，保留2位小数
function formatNumber(num) {
    if (num === null || num === undefined) return '--';
    return parseFloat(num).toFixed(2);
}

/**
 * 电机基本信息相关功能
 */
// 加载电机基本信息列表
function loadMotorBaseList(page = 0, size = 15) {
    const url = `${FEIBIAO_API_BASE}/${API_PATHS.motorBase}?page=${page}&size=${size}`;
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderMotorBaseTable(data);
        })
        .catch(error => {
            console.error('获取电机基本信息失败:', error);
            showMessage('获取电机基本信息失败: ' + error.message, 'error');
        });
}

// 获取当前视图模式（表格或卡片）
function getViewMode() {
    return 'table';
}

// 设置视图模式
function setViewMode(mode) {
    loadMotorBaseList(0, 10, 'table');
}

// 渲染电机基本信息表格
function renderMotorBaseTable(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建头部HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机基本信息管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showMotorBaseForm()">新增</button>
            </div>
        </div>
        
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入电机ID或型号搜索...">
            <button class="search-btn" onclick="searchMotorBase()">搜索</button>
        </div>
        
        <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>电机ID</th>
                    <th>电机型号</th>
                    <th>生产厂商</th>
                    <th>生产日期</th>
                    <th>创建时间</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 填充数据行
    if (data.content && data.content.length > 0) {
        data.content.forEach(motor => {
            html += `
                <tr>
                    <td>${motor.motorId || ''}</td>
                    <td>${motor.motorType || ''}</td>
                    <td>${motor.manufacturer || ''}</td>
                    <td>${formatDateTime(motor.productionDate) || ''}</td>
                    <td>${formatDateTime(motor.createdAt) || ''}</td>
                    <td>${formatDateTime(motor.updatedAt) || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewMotorBase('${motor.motorId}')">查看</a>
                        <a href="javascript:void(0)" onclick="editMotorBase('${motor.motorId}')">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteMotorBase('${motor.motorId}')">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="7" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
            </tbody>
        </table>
        </div>
    `;
    
    // 添加分页控件
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${data.number <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number <= 0 ? 'void(0)' : 'loadMotorBaseList(' + (data.number - 1) + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === data.number) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadMotorBaseList(${i})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${data.number >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number >= data.totalPages - 1 ? 'void(0)' : 'loadMotorBaseList(' + (data.number + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

// 应用筛选
function applyFilters() {
    // 由于移除了筛选功能，此函数保留为空
}

// 重置筛选
function resetFilters() {
    // 由于移除了筛选功能，此函数保留为空
}

// 搜索电机基本信息
function searchMotorBase() {
    const keyword = document.getElementById('searchInput').value.trim();
    
    // 重置页码并加载数据
    const page = 0;
    const size = 15;
    
    // 构建搜索URL
    let url = `${FEIBIAO_API_BASE}/${API_PATHS.motorBase}/search?keyword=${encodeURIComponent(keyword)}&page=${page}&size=${size}`;
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderMotorBaseSearchResults(data, page);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

// 根据关键词搜索电机基本信息（带分页）
function searchMotorBaseWithPagination(keyword, page = 0, size = 15) {
    // 构建搜索URL
    let url = `${FEIBIAO_API_BASE}/${API_PATHS.motorBase}/search?keyword=${encodeURIComponent(keyword)}&page=${page}&size=${size}`;
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderMotorBaseSearchResults(data, page);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

// 渲染电机基本信息搜索结果
function renderMotorBaseSearchResults(data, currentPage = 0) {
    const mainContent = document.getElementById('mainContent');
    const keyword = document.getElementById('searchInput')?.value.trim() || '';
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机基本信息搜索结果</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadMotorBaseList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="search-tip" style="margin-bottom:10px;color:#888;">支持按电机ID或电机型号模糊搜索</div>
        <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>电机ID</th>
                    <th>电机型号</th>
                    <th>生产厂商</th>
                    <th>生产日期</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.motorId || ''}</td>
                    <td>${item.motorType || ''}</td>
                    <td>${item.manufacturer || ''}</td>
                    <td>${formatDateTime(item.productionDate)}</td>
                    <td>${formatDateTime(item.createdAt)}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewMotorBase('${item.motorId}')">查看</a>
                        <a href="javascript:void(0)" onclick="editMotorBase('${item.motorId}')">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteMotorBase('${item.motorId}')">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += `
            <tr>
                <td colspan="6" class="text-center">未找到匹配的结果</td>
            </tr>
        `;
    }
    
    html += `
            </tbody>
        </table>
        </div>
    `;
    
    // 添加分页控件
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${data.number <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number <= 0 ? 'void(0)' : 'searchMotorBaseWithPagination(\'' + keyword + '\', ' + (data.number - 1) + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === data.number) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="searchMotorBaseWithPagination('${keyword}', ${i})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${data.number >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number >= data.totalPages - 1 ? 'void(0)' : 'searchMotorBaseWithPagination(\'' + keyword + '\', ' + (data.number + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    mainContent.innerHTML = html;
}

// 显示电机基本信息表单
function showMotorBaseForm(data = null) {
    const isEdit = !!data;
    const mainContent = document.getElementById('mainContent');
    
    const formTitle = isEdit ? '编辑电机基本信息' : '新增电机基本信息';
    const submitButtonText = isEdit ? '更新' : '保存';
    
    // 格式化日期值
    let dateValue = '';
    if (isEdit && data.productionDate) {
        const date = new Date(data.productionDate);
        dateValue = date.toISOString().split('T')[0]; // 格式化为YYYY-MM-DD
    }
    
    // 构建表单HTML
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">${formTitle}</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadMotorBaseList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="form-container">
        <form id="motorBaseForm" class="data-form" onsubmit="preventDefault(); saveMotorBase(this, ${isEdit});">
            
            <div class="form-group">
                <label for="motorId">电机ID</label>
                <input type="text" id="motorId" name="motorId" class="form-control" value="${isEdit ? data.motorId : ''}" ${isEdit ? 'readonly' : 'required'}>
            </div>
            
            <div class="form-group">
                <label for="motorType">电机型号</label>
                <input type="text" id="motorType" name="motorType" class="form-control" value="${isEdit && data.motorType ? data.motorType : ''}">
            </div>
            
            <div class="form-group">
                <label for="manufacturer">生产厂商</label>
                <input type="text" id="manufacturer" name="manufacturer" class="form-control" value="${isEdit && data.manufacturer ? data.manufacturer : ''}">
            </div>
            
            <div class="form-group">
                <label for="productionDate">生产日期</label>
                <input type="date" id="productionDate" name="productionDate" class="form-control" value="${dateValue}">
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">${submitButtonText}</button>
                <button type="button" class="btn btn-default" onclick="loadMotorBaseList()">取消</button>
            </div>
        </form>
        </div>
    `;
}

// 保存电机基本信息
function saveMotorBase(form, isEdit) {
    // 表单验证
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // 收集表单数据
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });
    
    // 构建请求
    const url = isEdit 
        ? `${FEIBIAO_API_BASE}/${API_PATHS.motorBase}/${data.motorId}` 
        : `${FEIBIAO_API_BASE}/${API_PATHS.motorBase}`;
    
    const method = isEdit ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应错误');
        }
        return response.json();
    })
    .then(() => {
        showMessage(`${isEdit ? '更新' : '创建'}电机基本信息成功`, 'success');
        loadMotorBaseList();
    })
    .catch(error => {
        console.error(`${isEdit ? '更新' : '创建'}电机基本信息失败:`, error);
        showMessage(`${isEdit ? '更新' : '创建'}失败: ` + error.message, 'error');
    });
}

// 查看电机基本信息详情
function viewMotorBase(motorId) {
    fetch(`${FEIBIAO_API_BASE}/${API_PATHS.motorBase}/${motorId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showMotorBaseDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

// 显示电机基本信息详情
function showMotorBaseDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机基本信息详情</h2>
            <button class="btn btn-default" onclick="loadMotorBaseList()"><i class="fa fa-list"></i> 返回列表</button>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>电机ID:</label><div>${data.motorId || '--'}</div></div>
            <div class="detail-group"><label>电机型号:</label><div>${data.motorType || '--'}</div></div>
            <div class="detail-group"><label>生产厂商:</label><div>${data.manufacturer || '--'}</div></div>
            <div class="detail-group"><label>生产日期:</label><div>${formatDateTime(data.productionDate) || '--'}</div></div>
            <div class="detail-group"><label>创建时间:</label><div>${formatDateTime(data.createdAt) || '--'}</div></div>
            <div class="detail-group"><label>更新时间:</label><div>${formatDateTime(data.updatedAt) || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editMotorBase('${data.motorId}')"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteMotorBase('${data.motorId}')"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadMotorBaseList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

// 编辑电机基本信息
function editMotorBase(motorId) {
    fetch(`${FEIBIAO_API_BASE}/${API_PATHS.motorBase}/${motorId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showMotorBaseForm(data);
        })
        .catch(error => {
            console.error('获取编辑信息失败:', error);
            showMessage('获取编辑信息失败: ' + error.message, 'error');
        });
}

// 删除电机基本信息
function deleteMotorBase(motorId) {
    if (!confirm('确定要删除此电机基本信息吗？与之关联的所有数据也将被删除。')) {
        return;
    }
    
    fetch(`${FEIBIAO_API_BASE}/${API_PATHS.motorBase}/${motorId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应错误');
        }
        showMessage('删除电机基本信息成功', 'success');
        loadMotorBaseList();
    })
    .catch(error => {
        console.error('删除失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
    });
}

// 确保所有函数都是全局可访问的
if (typeof window !== 'undefined') {
    // 基本信息函数
    window.loadMotorBaseList = loadMotorBaseList;
    window.renderMotorBaseTable = renderMotorBaseTable;
    // window.renderTableView = renderTableView;
    window.viewMotorBase = viewMotorBase;
    window.editMotorBase = editMotorBase;
    window.deleteMotorBase = deleteMotorBase;
    window.searchMotorBase = searchMotorBase;
    window.searchMotorBaseWithPagination = searchMotorBaseWithPagination;
    window.showMotorBaseForm = showMotorBaseForm;
    window.saveMotorBase = saveMotorBase;
    window.showMotorBaseDetail = showMotorBaseDetail;
} 